import { ToastAndroid } from "react-native";
import io from "socket.io-client";

class Socket {
  socket = null;

  create () {
    if (this.socket != null) {
      return;
    }

    ToastAndroid.show("create", ToastAndroid.SHORT);

    this.socket = io("ws://10.127.202.103:8001", {
      transports: ["websocket"],
      autoConnect: false,
      reconnection: true,
      path: ''  //根目录
    });

    this.socket.on("connect", () => {
      ToastAndroid.show("connect", ToastAndroid.SHORT);

      this.socket.send("hello server!");
    });

    this.socket.on("reconnect", () => {
      ToastAndroid.show("reconnect", ToastAndroid.SHORT);

      this.socket.send("hello re server!");
    });

    this.socket.on("message", data => {
      ToastAndroid.show("Received " + data, ToastAndroid.SHORT);
    });

    this.socket.on("disconnect", () => {
      ToastAndroid.show("disconnect", ToastAndroid.SHORT);
    });

    this.socket.open();
  }

  send (data) {
    //这里可以判断是否已断开连接

    this.socket.send(data);
  }
}

const socket = new Socket();

export default socket;
